package com.ff.sca.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ff.kvm.common.dv.es.UserESDV;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.team.consumer.TeamConsumer;
import com.ff.sca.common.aoplog.ControllerLog;
import com.ff.sca.common.base.BaseController;
import com.ff.sca.common.codeenum.OperateModule;
import com.ff.sca.common.codeenum.OperateType;
import com.ff.sca.common.constant.Constant;
import com.ff.sca.common.entity.resmsg.LayuiTableResMsg;
import com.ff.sca.common.entity.resmsg.ResMsg;
import com.ff.sca.common.entity.ztree.UserNode;
import com.ff.sca.common.util.CharUtil;
import com.ff.sca.common.util.DateUtil;
import com.ff.sca.common.util.MD5Util;
import com.ff.sca.system.entity.KvmSysCode;
import com.ff.sca.system.service.IKvmSysCodeService;
import com.ff.sca.user.entity.*;
import com.ff.sca.user.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author gw123
 * @since 2018-11-16
 */
@Controller
@RequestMapping("/kvmUser")
public class KvmUserController extends BaseController {

    @Autowired
    private IKvmUserService userService;
    @Autowired
    private IKvmBlackListService blackListService;
    @Autowired
    private IKvmAccountLogService accountLogService;
    @Autowired
    private IKvmSysCodeService sysCodeService;
    @Autowired
    private IKvmAccountService accountService;
    @Autowired
    private TeamConsumer teamConsumer;
    @Autowired
    private IKvmUserDirectService userDirectService;
    @Autowired
    private IKvmTeamService teamService;

    /**
     * 后台注册用户（做测试用）
     *
     * @param per
     * @param smobile
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/registerUser", method = RequestMethod.POST)
    public ResMsg registerUser(KvmUser per, String smobile) {
        try {
            List<KvmUser> list = userService.selectList(new EntityWrapper<KvmUser>().eq("mobile", per.getUserCode()));
            if (list.size() == 0) {
                KvmUser sjuser = userService.selectOne(new EntityWrapper<KvmUser>().eq("mobile", smobile));
                if (sjuser == null && smobile.equals("888888")) {
                    per.setPollCode("888888");
                    per.setFloor(1);
                } else {
                    per.setFloor(sjuser.getFloor() + 1);
                    per.setPollCode(smobile);
                }
                per.setLoginPwd(MD5Util.getMD5String(per.getLoginPwd()));
                per.setDealPwd(MD5Util.getMD5String(per.getDealPwd()));
                per.setStatus(0);
                per.setRoleId(0);
                per.setCreateTime(new Date());
                per.setUserCode(per.getMobile());
                boolean result = userService.insert(per);
                if (result) {
                    String user_floor = redisService.getAppCache("user_floor");
                    if (per.getFloor() > Integer.parseInt(user_floor)) {
                        redisService.putAppCache("user_floor", per.getFloor().toString(), 9999999, TimeUnit.DAYS);
                    }
                    KvmUser curUser = userService.selectOne(new EntityWrapper<KvmUser>().eq("mobile", per.getMobile()));
                    //ES
                    UserESDV esuserdv = new UserESDV();
                    esuserdv.setUserId(curUser.getId());
                    esuserdv.setCreateTime(curUser.getCreateTime());
                    esuserdv.setFloor(curUser.getFloor());
                    esuserdv.setLv(curUser.getLv());
                    if (sjuser != null) {
                        esuserdv.setUpUserId(sjuser.getId());
                    }
                    esuserdv.setStatus(curUser.getStatus());
                    esuserdv.setTeamGiftLv(0);
                    esuserdv.setTeamProductLv(0);
                    teamConsumer.addUser(esuserdv);
                    //直推信息记录
                    if (sjuser != null) {
                        KvmUserDirect userDirect = new KvmUserDirect();
                        userDirect.setUserId(sjuser.getId());
                        userDirect.setDirectUserId(curUser.getId());
                        userDirect.setStatus(0);
                        userDirect.setCreateTime(new Date());
                        userDirectService.insert(userDirect);
                    }
                    //Account
                    KvmAccount account = new KvmAccount();
                    account.setUserId(curUser.getId());
                    account.setCreateTime(new Date());
                    boolean result2 = accountService.insert(account);
                    return resSuccess(null);
                } else {
                    return resAreadyExisted(null);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 修改用户等级信息
     *
     * @param per
     * @return
     */
    @ControllerLog(
            description = "等级信息修改",
            module = OperateModule.SUserManger,
            opType = OperateType.modify
    )
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/updUserLv", method = RequestMethod.POST)
    public ResMsg updUserLv(KvmUser per) {
        try {
            if (CharUtil.isNotEmpty(per.getId()) && CharUtil.isNotEmpty(per.getLv()) && CharUtil.isNotEmpty(per.getTeamGiftLv()) && CharUtil.isNotEmpty(per.getTeamProductLv())) {
                KvmUser user = userService.selectById(per.getId());
                user.setLv(per.getLv());
                user.setTeamGiftLv(per.getTeamGiftLv());
                user.setTeamProductLv(per.getTeamProductLv());
                UserESDV esuserdv = new UserESDV();
                esuserdv.setUserId(user.getId());
                esuserdv.setFloor(user.getFloor());
                esuserdv.setLv(user.getLv());
                esuserdv.setStatus(user.getStatus());
                esuserdv.setTeamGiftLv(user.getTeamGiftLv());
                esuserdv.setTeamProductLv(user.getTeamProductLv());
                KvmUser upUser = userService.selectOne(new EntityWrapper<KvmUser>().eq("user_code", per.getPollCode()));
                if (upUser != null) {
                    esuserdv.setUpUserId(upUser.getId());
                }
                Response<Boolean> resultES = teamConsumer.updateUserLv(esuserdv);
                if (resultES.getCode().equals("200")) {
                    Boolean result = userService.updateById(user);
                    if (result) {
                        //更新团队信息
                        KvmTeam team = teamService.selectOne(new EntityWrapper<KvmTeam>().eq("user_id", user.getId()));
                        team.setLv(user.getLv());
                        team.setgLv(user.getTeamGiftLv());
                        team.setpLv(user.getTeamProductLv());
                        teamService.updateById(team);
                        //更新团队统计信息redis
                        String redis_team_info = redisService.getAppCache("team_info_" + user.getUserCode());
                        if (CharUtil.isNotEmpty(redis_team_info)) {
                            TeamInfo redis_ti = JSONObject.toJavaObject(JSONObject.parseObject(redis_team_info), TeamInfo.class);
                            redis_ti.setLv(per.getLv());
                            redis_ti.setTeamGiftLv(per.getTeamGiftLv());
                            redis_ti.setTeamProductLv(per.getTeamProductLv());
                            KvmSysCode sysCode = sysCodeService.selectOne(new EntityWrapper<KvmSysCode>().eq("name", "sm_redis_cache_time"));
                            int time = 10;
                            if (sysCode != null) {
                                time = Integer.parseInt(sysCode.getCode());
                            }
                            redisService.putAppCache("team_info_" + user.getUserCode(), JSONObject.toJSONString(redis_ti), time, TimeUnit.MINUTES);
                        }
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 用户的资金流水
     *
     * @param page
     * @param size
     * @param per
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userAccountLog", method = RequestMethod.POST)
    public LayuiTableResMsg userAccountLog(Integer page, Integer size, KvmAccountLog per) {
        try {
            Page<KvmAccountLog> pageEntity = setPageInfo(page, size);
            EntityWrapper ew = new EntityWrapper<KvmAccountLog>();
            if (CharUtil.isNotEmpty(per.getType())) {
                ew.eq("type", per.getType());
            }
            if (CharUtil.isNotEmpty(per.getChangeType())) {
                ew.eq("change_type", per.getChangeType());
            }
            ew.orderBy("create_time", false);
            Page<KvmAccountLog> suserList = accountLogService.selectPage(pageEntity, ew);
            long total = accountLogService.selectCount(ew);
            return resTableSuccess(total, suserList.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
            return resTableError(0, e.getMessage());
        }
    }

    /**
     * 用户加入到黑名单
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "用户加入到黑名单",
            module = OperateModule.SUserManger,
            opType = OperateType.create
    )
    @ResponseBody
    @RequestMapping(value = "/user2BlackList", method = RequestMethod.POST)
    public ResMsg user2BlackList(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                int count = blackListService.selectCount(new EntityWrapper<KvmBlackList>().eq("user_id", id));
                if (count == 0) {
                    KvmUser user = userService.selectById(id);
                    KvmBlackList blist = new KvmBlackList();
                    blist.setUserId(id);
                    blist.setCreateTime(new Date());
                    if (CharUtil.isNotEmpty(user.getName())) {
                        blist.setUserName(user.getName());
                    } else {
                        blist.setUserName(user.getUserName());
                    }
                    blackListService.insert(blist);
                }
                return resSuccess(null);
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 团队等级升级
     *
     * @param userId
     * @param lv
     * @return
     */
    @ControllerLog(
            description = "团队等级升级",
            module = OperateModule.SUserManger,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/teamUpLv", method = RequestMethod.POST)
    public ResMsg teamUpLv(Integer userId, Integer lv) {
        try {
            if (CharUtil.isNotEmpty(userId) && CharUtil.isNotEmpty(lv)) {
                KvmUser user = userService.selectById(userId);
                if (lv > user.getLv()) {//只允许存在升级
                    user.setLv(lv);
                    boolean result = userService.updateById(user);
                    if (result) {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 团队列表
     *
     * @param page
     * @param size
     * @param userCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/teamUserList", method = RequestMethod.POST)
    public LayuiTableResMsg teamUserList(Integer page, Integer size, String userCode) {
        try {
            Page<KvmUser> pageEntity = setPageInfo(page, size);
            Map<String, Object> map = new HashMap();
            if (CharUtil.isNotEmpty(userCode)) {
                map.put("poll_code", userCode);
            } else {
                map.put("poll_code", Constant.sysPollCode);
            }
            Page<KvmUser> suserList = userService.selectPage(pageEntity, new EntityWrapper<KvmUser>().allEq(map));
            long total = userService.selectCount(new EntityWrapper<KvmUser>().allEq(map));
            return resTableSuccess(total, suserList.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
            return resTableError(0, e.getMessage());
        }
    }

    /**
     * 团队统计信息
     *
     * @param userCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/teamStatisticInfo", method = RequestMethod.POST)
    public ResMsg teamStatisticInfo(String userCode, String refresh) {
        try {
            if (CharUtil.isNotEmpty(userCode)) {
                String redis_team_info = redisService.getAppCache("team_info_" + userCode);
                if (CharUtil.isNotEmpty(redis_team_info) && CharUtil.isEmpty(refresh)) {
                    TeamInfo redis_ti = JSONObject.toJavaObject(JSONObject.parseObject(redis_team_info), TeamInfo.class);
                    return resSuccess(redis_ti);
                } else {
                    TeamInfo ti = new TeamInfo();
                    ti.setTeamUserName(userCode);
                    KvmUser user = userService.selectOne(new EntityWrapper<KvmUser>().eq("user_code", userCode));
                    if (user != null) {
                        ti.setLv(user.getLv());//个人身份等级
                        ti.setTeamGiftLv(user.getTeamGiftLv());
                        ti.setTeamProductLv(user.getTeamProductLv());
                    }
                    ti.setTeamUserNum(userService.selectCount(new EntityWrapper<KvmUser>().eq("poll_code", userCode)));
                    ti.setTeamAllUserNum(userService.teamAllUserNum(userCode));
                    KvmSysCode sysCode = sysCodeService.selectOne(new EntityWrapper<KvmSysCode>().eq("name", "sm_redis_cache_time"));
                    int time = 10;
                    if (sysCode != null) {
                        time = Integer.parseInt(sysCode.getCode());
                    }
                    redisService.putAppCache("team_info_" + userCode, JSONObject.toJSONString(ti), time, TimeUnit.MINUTES);
                    return resSuccess(ti);
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 团队树形菜单
     *
     * @param userCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/teamZtree", method = RequestMethod.POST)
    public ResMsg teamZtree(String userCode) {
        try {
            if (CharUtil.isEmpty(userCode)) {
                userCode = "888888";
            }
            List<UserNode> userZtree = userService.teamZtree(userCode);
            return resSuccess(userZtree);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }


    /**
     * 修改用户信息
     *
     * @param per
     * @return
     */
    @ControllerLog(
            description = "修改用户信息",
            module = OperateModule.SUserManger,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/updUserInfo", method = RequestMethod.POST)
    public ResMsg updUserInfo(KvmUser per) {
        try {
            if (CharUtil.isNotEmpty(per.getId())) {
                KvmUser user = userService.selectById(per.getId());
                if (user != null) {
                    user.setNickName(per.getNickName());
                    user.setUserName(per.getUserName());
                    user.setName(per.getName());
                    user.setMobile(per.getMobile());
                    user.setStatus(per.getStatus());
                    user.setLv(per.getLv());
                    user.setTeamGiftLv(per.getTeamGiftLv());
                    user.setTeamProductLv(per.getTeamProductLv());
                    user.setAlipay(per.getAlipay());
                    user.setIdCard(per.getIdCard());
                    user.setUpdateTime(new Date());
                    boolean result = userService.updateById(user);
                    if (result) {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 重置登录密码
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "重置登录密码",
            module = OperateModule.SUserManger,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/resetLoginPwd", method = RequestMethod.POST)
    public ResMsg resetLoginPwd(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmUser user = userService.selectById(id);
                if (user != null) {
                    user.setLoginPwd(MD5Util.getMD5String("7777777"));
                    boolean result = userService.updateById(user);
                    if (result) {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 重置交易密码
     *
     * @param id
     * @return
     */
    @ControllerLog(
            description = "重置交易密码",
            module = OperateModule.SUserManger,
            opType = OperateType.modify
    )
    @ResponseBody
    @RequestMapping(value = "/resetDealPwd", method = RequestMethod.POST)
    public ResMsg resetDealPwd(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                KvmUser user = userService.selectById(id);
                if (user != null) {
                    user.setDealPwd(MD5Util.getMD5String("7777777"));
                    boolean result = userService.updateById(user);
                    if (result) {
                        return resSuccess(null);
                    }
                }
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 查看用户详情
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userInfo", method = RequestMethod.POST)
    public ResMsg userInfo(Integer id) {
        try {
            if (CharUtil.isNotEmpty(id)) {
                return resSuccess(userService.selectById(id));
            }
            return resfail(null);
        } catch (Exception e) {
            e.printStackTrace();
            return resError(e.getMessage());
        }
    }

    /**
     * 用户列表
     *
     * @param page
     * @param size
     * @param per
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userList", method = RequestMethod.POST)
    public LayuiTableResMsg userList(Integer page, Integer size, KvmUser per) {
        try {
            Page<KvmUser> pageEntity = setPageInfo(page, size);
            EntityWrapper ew = new EntityWrapper<KvmUser>();
            //Map<String, Object> map = new HashMap();
            //ew.allEq(map);
            if (CharUtil.isNotEmpty(per.getMobile())) {
                ew.like("mobile", per.getMobile());
            }
            if (CharUtil.isNotEmpty(per.getUserName())) {
                ew.like("user_name", per.getUserName());
            }
            if (CharUtil.isNotEmpty(per.getUserName())) {
                ew.like("name", per.getName());
            }
            Page<KvmUser> suserList = userService.selectPage(pageEntity, ew);
            long total = userService.selectCount(ew);
            return resTableSuccess(total, suserList.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
            return resTableError(0, e.getMessage());
        }
    }


}

